package com.sunny.ihealth.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.sunny.ihealth.BaseFragment;
import com.sunny.ihealth.R;
import com.sunny.ihealth.ui.activity.PostDetailActivity;
import com.sunny.ihealth.ui.adapter.OnViewClickListener;
import com.sunny.ihealth.ui.adapter.ZoneAdapter;
import com.sunny.ihealth.data.BmobManager;
import com.sunny.ihealth.entity.bmob.Post;
import com.sunny.ihealth.entity.bmob.State;
import com.sunny.ihealth.entity.eventbus.PostUpdateEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;


public class TabZoneFragment extends BaseFragment implements OnViewClickListener,
        SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "TAG::TabZoneF";
    //一次加载多少
    private static final int LOAD_ITEM_SIZE = 5;

    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ZoneAdapter adapter;
    private List<Post> data;
    //标志位，是否正在加载数据
    private boolean isLoading = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zone, container, false);
        initViews(view);
        return view;
    }

    @Override
    public void initViews(View v) {
        recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView_post);
        recyclerView.addOnScrollListener(onScrollListener);
        swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.refresh_post);
        swipeRefreshLayout.setOnRefreshListener(this);
        adapter = new ZoneAdapter(getActivity(), data = new ArrayList<>());
        adapter.setListener(this);
        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //显示刷新图标
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                initData(0, LOAD_ITEM_SIZE, null);
            }
        }, 1000);

    }

    /**
     * 加载数据
     *
     * @param skip  跳过多少
     * @param limit 加载多少
     */
    public void initData(final int skip, int limit, final Integer afterID) {
        isLoading = true;

        getBmob().getPost(skip, limit, afterID, new BmobManager.Action1<List<Post>>() {
            @Override
            public void onCompleted(List<Post> posts) {
                if (posts != null) {
                    if (posts.size() == 0) {
                        Toast.makeText(getContext(), "啊偶，什么都没加载出来~", Toast.LENGTH_SHORT).show();
                    } else {
                        if (afterID == null) { //刷新
                            data.clear();
                            data.addAll(posts);
                        } else { //加载
                            data.addAll(posts);
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
                isLoading = false;
                //延迟一段时间，隐藏刷新状态
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });
    }


    //RecyclerView的滑动状态监听
    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();

            //滑动到最后了
            if (!swipeRefreshLayout.isRefreshing() && !isLoading) {
                //滑动到最后了
                if (lastVisiblePosition + 1 == adapter.getItemCount() && dy > 0 && lastVisiblePosition != RecyclerView.NO_POSITION) {
                    //刷新数据
                    swipeRefreshLayout.setRefreshing(true);
                    //下拉加载的数据，要比最后一条时间要靠前
                    if (data.size() != 0) {
                        initData(0, LOAD_ITEM_SIZE, data.get(data.size() - 1).getId());
                    }
                }
            }
        }

    };

    @Override
    public void onViewClick(int which, final int position) {
        switch (which) {
            case R.id.btn_post_like://点赞按钮
                getBmob().likePost(data.get(position).getObjectId(), new BmobManager.Action1<State>() {
                    @Override
                    public void onCompleted(State state) {
                        if (state.getState() == State.STATE_DO_SUCCESSFUL) {
                            adapter.setLikeBtnText(true, position);
                        } else if (state.getState() == State.STATE_UNDO_SUCCESSFUL) {
                            adapter.setLikeBtnText(false, position);
                        } /*else {
                            Toast.makeText(getContext(), "点赞失败...", Toast.LENGTH_SHORT).show();
                        }*/
                    }
                });
                break;
            case R.id.btn_post_comment://评论按钮
            case R.id.ll_post_item:
                Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                intent.putExtra("data", data.get(position));
                intent.putExtra("position", position);
                startActivity(intent);
                break;
            case R.id.tv_post_addFriend://加关注
                getBmob().addFriend(data.get(position).getAuthor().getObjectId(), new BmobManager.Action1<State>() {
                    @Override
                    public void onCompleted(State state) {
                        if (state.getState() > 0) {
                            adapter.setIsFriend(state.getState(), position);
                        }
                    }
                });
        }
    }

    @Override
    public void onRefresh() {
        initData(0, LOAD_ITEM_SIZE, null);
    }


    /**
     * EventBus监听帖子改变
     */
    @Subscribe
    public void onPostUpdate(PostUpdateEvent event) {
        //关注状态是否改变
        int state = data.get(event.getPosition()).getAuthor().isFriend();
        if (state != event.getPost().getAuthor().isFriend()) {
            //使相同用户的关注状态一致
            adapter.setIsFriend(event.getPost().getAuthor().isFriend(), event.getPosition());
        }
        data.set(event.getPosition(), event.getPost());
        adapter.notifyItemChanged(event.getPosition());
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
